package com.xiaohong.user.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaohong.mq.feign.MqSenderFeign;
import com.xiaohong.mq.pojo.SendMsg;
import com.xiaohong.user.pojo.Friend;
import com.xiaohong.user.pojo.User;
import com.xiaohong.user.service.ChatFriendService;
import com.xiaohong.user.service.ChatUserService;
import com.xiaohong.websocket.feign.ChatCentreFeigh;
import entity.Result;
import entity.StatusCode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Tag(name = "ChatFriend接口文档")
@RestController
@RequestMapping("/chatFriend")
@CrossOrigin
public class ChatFriendController {

    @Autowired
    private ChatFriendService chatFriendService;

    @Autowired
    private ChatUserService chatUserService;

    @Autowired
    private MqSenderFeign mqSenderFeign;

    @Autowired
    private ChatCentreFeigh chatCentreFeigh;


    /***
     * 分页条件搜索实现ChatFriend
     * @param friend
     * @param page
     * @param size
     * @return
     */
    @Operation(summary = "条件分页查询ChatFriend",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameters({
            @Parameter(in = ParameterIn.PATH, name = "page", description = "当前页", required = true),
            @Parameter(in = ParameterIn.PATH, name = "size", description = "每页显示条数", required = true)
    })
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<Page> findPage(@RequestBody(required = false) @Parameter(name = "ChatFriend对象",required = true) Friend friend, @PathVariable int page, @PathVariable  int size){
        //调用ChatFriendService实现分页条件查询ChatFriend
        Page pageInfo = chatFriendService.findPage(friend, page, size);
        return new Result<Page>(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     * 分页搜索实现ChatFriend
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @Operation(summary = "分页查询ChatFriend",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameters({
            @Parameter(in = ParameterIn.PATH, name = "page", description = "当前页", required = true),
            @Parameter(in = ParameterIn.PATH, name = "size", description = "每页显示条数", required = true)
    })
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<Page> findPage(@PathVariable  int page, @PathVariable  int size){
        //调用ChatFriendService实现分页查询ChatFriend
        Page pageInfo = chatFriendService.findPage(page, size);
        return new Result<Page>(true,StatusCode.OK,"查询成功",pageInfo);
    }

    /***
     * 多条件搜索ChatFriend数据
     * @param friend
     * @return
     */
    @Operation(summary = "多条件查询ChatFriend",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping(value = "/search" )
    public Result<List<Friend>> findList(@RequestBody(required = false) @Parameter(name = "ChatFriend对象",required = true) Friend friend){
        //调用ChatFriendService实现条件查询ChatFriend
        List<Friend> list = chatFriendService.findList(friend);
        return new Result<List<Friend>>(true,StatusCode.OK,"查询成功",list);
    }

    /***
     * 根据Id删除chatFriend数据
     * @param id
     * @return
     */
    @Operation(summary = "根据ID删除ChatFriend",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameter(in = ParameterIn.PATH, name = "id", description = "删除对象ID", required = true)
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Long id){
        //调用ChatFriendService实现根据ID删除
        chatFriendService.delete(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /***
     * 根据ID修改ChatFriend数据
     * @param friend
     * @param id
     * @return
     */
    @Operation(summary = "根据ID修改ChatFriend",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameter(in = ParameterIn.PATH, name = "id", description = "修改对象ID", required = true)
    @PutMapping(value = "/{id}" )
    public Result update(@RequestBody @Parameter(name = "ChatFriend对象",required = true) Friend friend, @PathVariable Long id){
        // 补充id
        friend.setId(id);
        //调用ChatFriendService实现修改ChatFriend
        chatFriendService.update(friend);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    /***
     * 新增ChatFriend数据
     * @param friend
     * @return
     */
    @Operation(summary = "添加ChatFriend",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping
    public Result add(@RequestBody  @Parameter(name = "ChatFriend对象",required = true) Friend friend){
        //调用ChatFriendService实现添加ChatFriend
        chatFriendService.add(friend);
        return new Result(true,StatusCode.OK,"添加成功");
    }

    /***
     * 获取好友信息
     * @param uid
     * @param fid
     * @param index 下标，前端同步用
     * @return
     */
    @Operation(summary = "获取好友信息",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameters({
            @Parameter(in = ParameterIn.PATH, name = "uid", description = "用户id", required = true),
            @Parameter(in = ParameterIn.PATH, name = "fid", description = "好友id", required = true),
            @Parameter(in = ParameterIn.PATH, name = "index", description = "下标，前端同步用", required = true)
    })
    @GetMapping("/{uid}/{fid}/{index}")
    public Result<User> findById(@PathVariable Long uid,@PathVariable Long fid,@PathVariable Integer index){
        Friend fd = new Friend();
        fd.setUserId(uid);
        fd.setFriendId(fid);
        if (isFriend(fd).getData()){
            User byId = chatUserService.findById(fid);
            if(byId != null){
                byId.setIndex(index);
                byId.setStatus(chatCentreFeigh.getStatus(fid).getData());
            }
            return new Result<User>(true,StatusCode.OK,"查询成功", byId);
        }else{
            // 非好友
            return new Result<User>(true,StatusCode.ERROR,"你们还不是好友哦！");
        }
    }

    /**
     * 删除好友
     * @param fd
     * @return
     */
    @Operation(summary = "删除好友",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @DeleteMapping("/delFriend")
    public Result delFriend(@RequestBody @Parameter(name = "ChatFriend对象",required = true) Friend fd){
        try {
            Long user = fd.getUserId();
            Long friend = fd.getFriendId();
            Friend fd2 = new Friend();
            fd2.setFriendId(friend);
            fd2.setUserId(user);
            if (isFriend(fd).getData()){
                // 双向删除
                chatFriendService.delete(chatFriendService.findList(fd).get(0).getId());
                chatFriendService.delete(chatFriendService.findList(fd2).get(0).getId());
                // 通知对方
                SendMsg sendMsg = new SendMsg();
                sendMsg.setSender(user+"");
                sendMsg.setReceiver(friend+"");
                sendMsg.setContent("对方已将您删除");
                sendMsg.setHeart(false);
                mqSenderFeign.send(JSON.toJSONString(sendMsg));
                return new Result(true,StatusCode.OK,"删除好友成功！");
            }else {
                // 非好友
                return new Result(false,StatusCode.ERROR,"你和对方不是好友哦！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"删除好友失败！");
        }


    }

    /**
     * 添加好友
     * @param fd
     * @return
     */
    @Operation(summary = "添加好友",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/addFriend")
    public Result addFriend(@RequestBody @Parameter(name = "ChatFriend对象",required = true) Friend fd) {
        try {
            if(!isFriend(fd).getData()){
                Long user = fd.getUserId();
                Long friend = fd.getFriendId();
                String groupNameEN = fd.getGroupNameEN();
                String groupNameCH = fd.getGroupNameCH();
                Friend fd2 = new Friend();
                // 双向添加
                fd2.setUserId(friend);
                fd2.setFriendId(user);
                fd2.setGroupNameEN(groupNameEN);
                fd2.setGroupNameCH(groupNameCH);
                chatFriendService.add(fd);
                chatFriendService.add(fd2);
                return new Result(true,StatusCode.OK,"添加好友成功！");
            }else {
                return new Result(true,StatusCode.ERROR,"你和对方已是好友哦！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"添加好友失败！");
        }
    }


    /**
     * 判断是否是好友
     * @param fd
     * @return
     */
    @Operation(summary = "判断是否是好友",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/isFriend")
    public Result<Boolean> isFriend(@RequestBody @Parameter(name = "ChatFriend对象",required = true) Friend fd){
        Long user = fd.getUserId();
        Long friend = fd.getFriendId();
        Friend find = new Friend();
        find.setUserId(user);
        find.setFriendId(friend);
        List<Friend> result = chatFriendService.findList(find);
        if (result != null && result.size() > 0){
            find.setUserId(friend);
            find.setFriendId(user);
            List<Friend> list = chatFriendService.findList(find);
            if ( list != null && list.size() > 0){
                // 好友
                return new Result<Boolean>(true,StatusCode.OK,"你和对方是好友哦",true);
            }else {
                // 非好友
                return new Result<Boolean>(true,StatusCode.OK,"你和对方还不是好友哦",false);
            }
        }else {
            // 非好友
            return new Result<Boolean>(true,StatusCode.OK,"你和对方还不是好友哦",false);
        }
    }

    /**
     * 获取用户好友分类列表
     * @param id
     * @return
     */
    @Operation(summary = "分类查询指定用户的指定好友分类用户列表",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameter(in = ParameterIn.PATH, name = "id", description = "用户ID", required = true)
    @GetMapping("/friendList/{id}")
    public Result<List<User>> getFriendList(@PathVariable Long id){
        // 获取该分组好友
        Friend friend = new Friend();
        friend.setUserId(id);
        List<Friend> list = chatFriendService.findList(friend);
        // 获取每个好友的信息
        List<User> userList = new ArrayList<>();
        if (list != null && list.size() > 0){
            for (Friend fd : list) {
                User byId = chatUserService.findById(fd.getFriendId());
                if (byId != null){
                    byId.setGroupNameCH(fd.getGroupNameCH());
                    byId.setGroupNameEN(fd.getGroupNameEN());
                    byId.setStatus(chatCentreFeigh.getStatus(fd.getFriendId()).getData());
                    userList.add(byId);
                }else {
                    System.out.println(fd.getFriendId()+"的信息为空");
                }
            }
            return new Result<List<User>>(true,StatusCode.OK,"获取好友列表成功",userList);
        }else {
            return new Result<List<User>>(true,StatusCode.OK,"获取好友列表成功",null);
        }
    }

    /**
     * 获取指定好友分类列表
     * @param id
     * @param group
     * @return
     */
    @Operation(summary = "分类查询指定用户的指定好友分类用户列表",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @Parameters({
            @Parameter(in = ParameterIn.PATH, name = "id", description = "用户ID", required = true),
            @Parameter(in = ParameterIn.PATH, name = "group", description = "好友分组", required = true)
    })
    @GetMapping("/friendList/{id}/{group}")
    public Result<List<User>> getFriendListByGroup(@PathVariable Long id, @PathVariable String group){
        // 获取该分组好友
        Friend friend = new Friend();
        friend.setUserId(id);
        friend.setGroupNameEN(group);
        List<Friend> list = chatFriendService.findList(friend);
        // 获取每个好友的信息
        List<User> userList = new ArrayList<>();
        if (list != null && list.size() > 0){
            for (Friend fd : list) {
                User byId = chatUserService.findById(fd.getFriendId());
                if (byId != null){
                    byId.setStatus(chatCentreFeigh.getStatus(fd.getFriendId()).getData());
                    userList.add(byId);
                }else {
                    System.out.println(fd.getFriendId()+"的信息为空");
                }
            }
            return new Result<List<User>>(true,StatusCode.OK,"获取好友列表成功",userList);
        }else {
            return new Result<List<User>>(true,StatusCode.OK,"获取好友列表成功",null);
        }
    }

    /***
     * 查询ChatFriend全部数据
     * @return
     */
    @Operation(summary = "查询所有ChatFriend",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @GetMapping
    public Result<List<Friend>> findAll(){
        //调用ChatFriendService实现查询所有ChatFriend
        List<Friend> list = chatFriendService.findAll();
        return new Result<List<Friend>>(true, StatusCode.OK,"查询成功",list) ;
    }
}
